﻿using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IdleTestServer
{
    /// <summary>
    /// MessageToByteEncoder:消息编码到字节,编码成字节数组形式
    /// </summary>
    public class IdleTestServerHandler : MessageToByteEncoder<string>  //这里的泛型代表:你设置了什么类型,那我检查到该类型,我就进行相应的编码。
    {
        /// <summary>
        /// 当Netty中的读写空闲（超时）后,会调用userEventTriggered方法,覆写这个方法就可以对心跳超时进行一定的逻辑处理。
        /// </summary>
        /// <param name="context"></param>
        /// <param name="evt"></param>
        public override void UserEventTriggered(IChannelHandlerContext context, object evt)
        {
            if (evt is IdleStateEvent)
            {
                IdleStateEvent? e = evt as IdleStateEvent;
                string eType = string.Empty;
                switch (e!.State)
                {
                    case IdleState.ReaderIdle:  // 读空闲
                        eType = "读空闲";
                        break;
                    case IdleState.WriterIdle:  // 写空闲
                        eType = "写空闲";
                        break;
                    case IdleState.AllIdle:     // 读写空闲
                        eType = "读写空闲";
                        break;
                    default:
                        break;
                }

                // context.Channel.RemoteAddress:客户端地址
                Console.WriteLine(context.Channel.RemoteAddress + "超时事件" + eType);
            }


        }

        protected override void Encode(IChannelHandlerContext context, string message, IByteBuffer output)
        {

        }

        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            Console.WriteLine(message);
        }
    }
}
